import React, { Component, PropTypes } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Linking,
  DeviceEventEmitter,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import PxToDp from '../../utils/PxToDp';
import FontFamilys from '../../utils/FontFamilys';
import fetchCollect from '../../actions/saleChanceActions';
import { fetchLockUser } from '../../actions/communicateAction';
import MyCustomerDetails from '../../containers/MyCustomerDetailContainer';
import UserStageBtn from '../../containers/UserStageContainer';
import ModalExt from '../Public/ModalExt';
import CommunicationOnline from '../../containers/CommunicateContainer';


/* global homeWs */
let startSelectMy = 0;
let voiceOnline = 0;

class myCustomerItem extends Component {
  static propTypes = {
    saleData: PropTypes.object,
  };
  constructor(props) {
    super(props);
    this.state = {
      customerCollect: 0,
      modalShowMy: false,
      call: false,
    };
  }
  /**
    *点击收藏
    */
  collect() {
    let id = '';
    if (this.props.saleData) {
      id = this.props.saleData.id;
      if (this.props.saleData.collect) {
        this.props.saleData.collect = 0;
        this.setState({ customerCollect: 0 });
        startSelectMy = 0;
      } else {
        this.props.saleData.collect = 1;
        this.setState({ customerCollect: 1 });
        startSelectMy = 1;
      }
      this.props.dispatch(fetchCollect(id, this.props.saleData.collect));
    }
  }
  /*
  *用户阶段
  */
  stageValue(code) {
    switch (code) {
      case 1:
        return '初步沟通';
      case 2:
        return '已报价';
      case 3:
        return '试驾预约';
      case 4:
        return '到店体验';
      case 5:
        return '已成交';
      case 6:
        return '放弃购买';
      case 7:
        return '其他';
      default:
        return '';
    }
  }

  callMe(tel) {
    Linking.openURL(`tel:${tel}`).catch((e) => {
      console.log(e);
    },
    );
  }

  _gotTodetails(id) {
    const dispatch = this.props.navigator.dispatch;
    const { saleData } = this.props;
    const user = saleData;
    const userType = 'myCustomer';
    this.props.navigator.navigator.push({
      component: MyCustomerDetails,
      passProps: { dispatch, id, userType, user },
    });
  }

  _setModalVisible(visible) {
    this.setState({ modalShowMy: visible });
  }

  _setModalCall(visible) {
    this.setState({ call: visible });
  }

  // 进入在线沟通页面
  _goCommunicationOnline() {
    const { dispatch, saleData } = this.props;
    const user = saleData;
    if (homeWs) {
      homeWs.send(JSON.stringify({ uid: user.id }));
    }
    this.props.dispatch(fetchLockUser(user.id, (data) => {
      if (data && data.lock) {
        this.props.navigator.navigator.push({
          component: CommunicationOnline,
          passProps: { user, dispatch },
        });
      } else {
        DeviceEventEmitter.emit('showToast', data.err);
      }
    }));
  }

  render() {
    const { saleData } = this.props;
    // const visit = this.props.visit ? this.props.visit : null;
    // const { reminds } = visit;
    let id = '';
    if (saleData && saleData.hasOwnProperty) {
      id = saleData.id;
    }
    // const remind = reminds && reminds[0].user_id === id ?
    //       reminds[0] : saleData.remind ? saleData.remind : null;

    let username = '';
    let sex = '男';
    let address = '';
    let loginAt = '';
    let age = '';
    let lookcar = '';
    let bookdrive = '';
    let stage = '';
    let nameImg = '';
    let phone = '';
    let stageNum = '';

    if (saleData) {
      username = saleData.username;
      if (username) {
        nameImg = username.substring(username.length - 2, username.length);
      }
      sex = saleData.sex === '男' ? require('../../img/home/cule-list-men.png') : require('../../img/home/cule-list-wamen.png');
      address = saleData.address;
      loginAt = saleData.login_at;
      age = saleData.age;
      lookcar = saleData.lookcar;
      bookdrive = saleData.bookdrive;
      phone = saleData.phone;
      if (saleData.online) {
        voiceOnline = 1;
      } else {
        voiceOnline = 0;
      }
      if (saleData.collect === 1) {
        startSelectMy = 1;
      } else {
        startSelectMy = 0;
      }
    }
    if (this.props.userIdStore === saleData.id) {
      stageNum = this.props.stageObj;
      stage = this.stageValue(stageNum);
    } else if (saleData.stage) {
      stageNum = saleData.stage;
      stage = this.stageValue(stageNum);
    } else {
      stageNum = '';
    }
    return (
      <TouchableOpacity
        activeOpacity={0.6}
        navigator={this.props.navigator}
        onPress={() => this._gotTodetails(id)}
      >
        <View style={style.wrapper}>
          <View style={style.row}>
            <View style={style.contentLeft}>
              <View style={[style.avator, { backgroundColor: saleData.color_value }]} >
                <Text style={style.avatorText}>{nameImg}</Text>
              </View>
            </View>
            <View style={style.contentMid}>
              <View style={[style.row, { alignItems: 'center' }]}>
                <View>
                  <Text style={style.name}>{ username }</Text>
                </View>
                <View style={[style.red]}>
                  <Image source={sex} />
                </View>
                {stage
                  ?
                    <View style={style.yellow}>
                      <Text style={style.sexText}>
                        { stage }
                      </Text>

                    </View>
                  : null
                }
              </View>
              <View style={[style.row, style.contentTime]}>
                <Text style={[style.loginAt, style.textFontFamily]}>最近登录: {loginAt}</Text>
              </View>
            </View>
            <TouchableOpacity
              style={style.contentRight}
              onPress={() => this.collect()}
            >
              {startSelectMy === 1
                ?
                  <Image source={require('../../img/home/hStarFocus.png')} />
                :
                  <Image source={require('../../img/home/hStarNormal.png')} />
              }
            </TouchableOpacity>
          </View>

          <View style={[style.buyInfo, style.row, style.flexWrap]}>
            <Text style={[style.buyInfoBg, style.textFontFamily, style.buyInfoLeft]}>{phone}</Text>
            <Text style={[style.buyInfoBg, style.buyInfoLeft, style.textFontFamily]}>
              {address}
            </Text>
            <Text style={[style.buyInfoBg, style.buyInfoLeft, style.textFontFamily]}>{age}岁</Text>
            <Text style={[style.buyInfoBg, style.buyInfoLeft, style.textFontFamily]}>{saleData.has_plate ? '有车号' : '无车号'}</Text>
            <Text style={[style.buyInfoBg, style.buyInfoLeft, style.textFontFamily]}>{saleData.buy_at ? saleData.buy_at : ''}</Text>
            {
              saleData.budget_value
              ?
                <Text style={[style.buyInfoBg, style.buyInfoLeft, style.textFontFamily]}>{`预算${saleData.budget_value}左右`}</Text>
              :
              null

            }
            {
              saleData.buy_method
              ?
                <Text style={[style.buyInfoBg, style.textFontFamily, style.buyInfoLeft]}>
                  {saleData.buy_method}
                </Text>
              :
              null
            }

          </View>
          <View style={[style.row, style.carView]}>
            <Image source={require('../../img/home/cule-list-likecar.png')} />
            <Text style={[style.carText, style.car]}>关注车系：</Text>
            <Text style={style.carText}>{lookcar}</Text>
          </View>
          <View style={[style.row, style.intentView]}>
            <Image source={require('../../img/home/cule-list-likebuy.png')} />
            <Text style={[style.carText, style.car]}>
              购买意向：
            </Text>
            <Text style={style.carText}>{saleData && saleData.intention}%</Text>
          </View>
          <View style={[style.row, style.intentView]}>
            <Image source={require('../../img/home/cule-list-word.png')} />
            <Text style={[style.carText, style.car]}>
              预约试驾：
            </Text>
            <Text style={style.carText}>{bookdrive}</Text>
          </View>

          <View style={style.lineB}>
            <View style={style.lineBottom} />
          </View>
          <View style={[style.bottom, style.row]}>
            <View style={[style.leftBtn, style.row]}>
              <TouchableOpacity
                style={[style.buttonCall, style.buttonDeft]}
                onPress={() => this._setModalCall(true)}
              >
                <View style={[style.row]}>
                  <Image source={require('../../img/home/hPhone.png')} />
                  <Text style={[style.buttonTextClaim, style.textFontFamily]}>拨打电话</Text>
                </View>
              </TouchableOpacity>
              <View style={style.lineR} />
              <TouchableOpacity
                style={[style.buttonDeft, style.buttonStage]}
                onPress={() => this._setModalVisible(true)}
              >
                <View style={[style.row]}>
                  <Image source={require('../../img/home/hStap.png')} />
                  <Text style={[style.buttonTextClaim, style.textFontFamily]}>客户阶段</Text>
                </View>
              </TouchableOpacity>
              <View style={style.lineR} />
              {
              voiceOnline === 1
              ?
                <TouchableOpacity
                  style={[style.button, style.buttonChat]}
                  onPress={() => this._goCommunicationOnline()}
                >
                  <View style={style.row}>
                    <Image source={require('../../img/home/invalidName.png')} />
                    <Text style={[style.buttonTextChat, style.textFontFamily]}>在线沟通</Text>
                  </View>
                </TouchableOpacity>
              :
                <TouchableOpacity
                  disabled={false}
                  style={[style.buttonDeft, style.chatDeft]}
                >
                  <View style={style.row}>
                    <Image source={require('../../img/home/hVoiceDeft.png')} />
                    <Text style={[style.buttonTextClaim, style.textFontFamily, style.textDeft]}>
                      在线沟通
                    </Text>
                  </View>
                </TouchableOpacity>
            }
            </View>

          </View>
        </View>
        <ModalExt
          onRequestClose={() => this._setModalVisible(false)}
          animationType={'slide'}
          transparent
          visible={this.state.modalShowMy}
          onPress={() => this._setModalVisible(false)}
        >
          <UserStageBtn
            Comfirm={() => {
              this._setModalVisible(false);
            }}
            stageNum={stageNum}
            userId={this.props.saleData.id}
            dispatch={this.props.dispatch}
          />
        </ModalExt>

        <ModalExt
          style={style.flex} onRequestClose={() => this._setModalSale(false)}
          animationType={'slide'} transparent visible={this.state.call}
          onPress={() => this._setModalCall(false)}
        >
          <View style={[style.bgColor, style.flex]}>
            <LinearGradient
              colors={['#7b6aff', '#4cbbff']}
              style={style.linerModal}
              start={{ x: 0, y: 1 }}
              end={{ x: 1, y: 1 }}
            >
              <View style={[style.row, style.linerTitle]}>
                <View style={style.lineL} />
                <Text style={style.climT}>拨打电话</Text>
                <View style={style.lineL} />
              </View>

              <View style={style.climCon}>
                <Text style={style.climConT}>
                是否拨打{phone}?
              </Text>
              </View>
            </LinearGradient>
            <View style={[style.climBottm, style.row]}>
              <TouchableOpacity
                activeOpacity={0.6}
                style={[style.cancleBtn, style.modalBtn]}
                onPress={() => this._setModalCall(false)}
              >
                <Text style={style.cancleT}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                activeOpacity={0.6}
                style={[style.climBtn, style.modalBtn]}
                onPress={() => this.callMe(phone)}
              >
                <Text style={style.commitT}>拨打</Text>
              </TouchableOpacity>
            </View>
          </View>
        </ModalExt>
      </TouchableOpacity>

    );
  }
}

const style = StyleSheet.create({
  wrapper: {
    backgroundColor: '#fff',
    marginTop: PxToDp(10),
    paddingLeft: PxToDp(10),
    paddingRight: PxToDp(10),
  },
  row: {
    flexDirection: 'row',
  },
  contentLeft: {
    flex: 0.6,
    alignItems: 'flex-start',
    justifyContent: 'center',
    paddingLeft: PxToDp(12),
    marginTop: PxToDp(18),
  },
  avator: {
    width: PxToDp(38),
    height: PxToDp(38),
    borderRadius: PxToDp(18),
    backgroundColor: '#a978e5',
    alignItems: 'center',
    justifyContent: 'center',
  },
  avatorText: {
    color: '#fff',
    fontSize: PxToDp(12),
    marginTop: PxToDp(2),
  },
  contentMid: {
    flex: 3,
    justifyContent: 'center',
    marginTop: PxToDp(18),
  },
  contentRight: {
    alignItems: 'flex-end',
    paddingRight: PxToDp(19),
  },
  name: {
    fontSize: PxToDp(15),
    color: '#000000',
  },
  contentTime: {
    marginTop: PxToDp(2),
  },
  loginAt: {
    fontSize: PxToDp(10),
    color: '#999999',
    marginTop: PxToDp(2),
  },
  textFontFamily: {
    fontFamily: FontFamilys(),
  },
  sexText: {
    color: '#8b8c8e',
    fontSize: PxToDp(10),
    fontFamily: FontFamilys(),
  },
  red: {
    marginLeft: PxToDp(15),
    width: PxToDp(13),
    height: PxToDp(13),
  },
  buyInfo: {
    paddingLeft: PxToDp(11),
    paddingTop: PxToDp(14),
  },
  buyInfoBg: {
    backgroundColor: '#D6CEAA',
    borderRadius: PxToDp(1),
    paddingTop: PxToDp(3),
    paddingBottom: PxToDp(3),
    paddingLeft: PxToDp(7),
    paddingRight: PxToDp(7),
    fontSize: PxToDp(12),
    color: '#FFFFFF',
    height: PxToDp(22),
    marginBottom: PxToDp(5),
  },
  buyInfoLeft: {
    marginRight: PxToDp(8),
  },
  carView: {
    paddingTop: PxToDp(11),
    paddingLeft: PxToDp(11),
  },
  intentView: {
    paddingTop: PxToDp(8),
    paddingLeft: PxToDp(11),
  },
  carText: {
    fontSize: PxToDp(13),
    color: '#121212',
    fontFamily: FontFamilys(),
  },
  lineB: {
    marginTop: PxToDp(21),
    width: '100%',
    paddingRight: PxToDp(10),
    paddingLeft: PxToDp(10),
  },
  lineBottom: {
    height: PxToDp(1),
    backgroundColor: '#dadada',
  },
  bottom: {
    height: PxToDp(44),
    backgroundColor: '#FFFFFF',
    alignItems: 'center',
  },
  buttonDeft: {
    height: PxToDp(30),
    justifyContent: 'center',
  },
  buttonCall: {
    marginLeft: PxToDp(10),
  },
  button: {
    height: PxToDp(30),
    width: PxToDp(100),
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: PxToDp(100),
    borderStyle: 'solid',
    borderWidth: PxToDp(1),
  },
  buttonChat: {
    borderColor: '#2be79b',
    backgroundColor: '#2be79b',
    marginLeft: PxToDp(7),
  },
  buttonTextClaim: {
    fontSize: PxToDp(14),
    color: '#666666',
    marginLeft: PxToDp(4),
  },
  textDeft: {
    color: '#D4D5D9',
  },
  buttonTextChat: {
    fontSize: PxToDp(14),
    color: '#FFFFFF',
  },
  yellow: {
    backgroundColor: '#efefef',
    marginLeft: PxToDp(8),
    paddingLeft: PxToDp(12),
    paddingRight: PxToDp(12),
    height: PxToDp(17),
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: PxToDp(8),
  },
  car: {
    marginLeft: PxToDp(9),
  },
  chatDeft: {
    marginLeft: PxToDp(16),
  },
  lineR: {
    backgroundColor: '#e4e4e4',
    height: PxToDp(15),
    width: PxToDp(1),
    marginLeft: PxToDp(16),
    marginTop: PxToDp(8),
  },
  buttonStage: {
    marginLeft: PxToDp(16),
  },
  leftBtn: {
    flex: 10,
  },
  flexWrap: {
    flexWrap: 'wrap',
  },
  flex: {
    flex: 1,
  },
  linerModal: {
    width: PxToDp(285),
    height: PxToDp(176),
    paddingTop: PxToDp(21),
  },
  linerTitle: {
    height: PxToDp(22),
    alignItems: 'center',
    paddingLeft: PxToDp(18),
    paddingRight: PxToDp(18),
  },
  lineL: {
    width: PxToDp(80),
    backgroundColor: '#a5c9ec',
    height: PxToDp(1),
  },
  climCon: {
    alignItems: 'center',
    marginTop: PxToDp(35),
  },
  climBottm: {
    height: PxToDp(86),
    width: PxToDp(285),
    backgroundColor: '#FFF',
    paddingLeft: PxToDp(30),
    paddingRight: PxToDp(30),
    paddingTop: PxToDp(24),
  },
  climBtn: {
    borderColor: '#458fff',
    marginLeft: PxToDp(24),
  },
  cancleBtn: {
    borderColor: '#dddddd',
  },
  modalBtn: {
    width: PxToDp(101),
    height: PxToDp(38),
    borderRadius: PxToDp(100),
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: PxToDp(1),
    borderStyle: 'solid',
  },
  commitT: {
    color: '#458fff',
    fontSize: PxToDp(16),
    fontFamily: FontFamilys(),
  },
  cancleT: {
    color: '#8b8c8e',
    fontSize: PxToDp(16),
    fontFamily: FontFamilys(),
  },
  climT: {
    color: '#ffffff',
    fontFamily: FontFamilys(),
    fontSize: PxToDp(16),
    backgroundColor: 'transparent',
    marginLeft: PxToDp(12),
    marginRight: PxToDp(12),
  },
  bgColor: {
    backgroundColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: '#F65252',
  },
  climConT: {
    color: '#c4d2ff',
    fontSize: PxToDp(14),
    fontFamily: FontFamilys(),
    backgroundColor: 'transparent',
  },
});
export default myCustomerItem;
